package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.utils.SPUtils;
import com.longqinuo.mycarservice.view.CircleNetworkImage;
import com.longqinuo.mycarservice.view.LruImageCache;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link UserFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserFragment extends Fragment implements View.OnClickListener{
    private static RequestQueue queue;
    private static ImageLoader imageLoader;
    private ListView mListView;
    private SimpleAdapter mAdapter;
    private List<Map<String,Object>> mList;
    private static CircleNetworkImage mHeader;
    private String headerUrl;
    private int images[] = {R.mipmap.my_car,R.mipmap.my_collection,
            R.mipmap.my_publish,R.mipmap.my_recommend,R.mipmap.my_setting};
    private String texts[] = {"我的车辆","我的收藏","我发表的","推荐给朋友","设置"};
    private static TextView mLogin;
    private FragmentManager manager;
    private FragmentTransaction mTransaction;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public UserFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static UserFragment newInstance(String param1, String param2) {
        UserFragment fragment = new UserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        init();
    }

    private void init() {
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue,lruImageCache);

        manager = getActivity().getSupportFragmentManager();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (PathUtils.havedLogin) {
            mLogin.setText((String) SPUtils.getSp(getActivity(),"userName","点击登陆"));
            headerUrl = PathUtils.LOAD_HEADER+SPUtils.getSp(getActivity(),"headerPath","");
            mHeader.setImageUrl(headerUrl,imageLoader);
        }else {
            Toast.makeText(getActivity(), "当前未登录，登录后获取更多功能", Toast.LENGTH_SHORT).show();
        }
    }

    public static void  setUserName(String userPhone ) {
        if (mLogin!=null) {

            mLogin.setText(userPhone);
            mLogin.setClickable(false);
        }

    }
    public static void setUserHeader(String url) {
        if (mHeader!=null) {
            mHeader.setImageUrl(url, imageLoader);
        }
    }
    private void initView(View view) {
        mHeader = (CircleNetworkImage) view.findViewById(R.id.cni_header_user);
        mHeader.setOnClickListener(this);
        manager = getActivity().getSupportFragmentManager();
        mListView = (ListView) view.findViewById(R.id.lv_user_menu);
        mLogin = (TextView) view.findViewById(R.id.tv_click_login);
        mLogin.setOnClickListener(this);

        initDate();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTransaction = manager.beginTransaction();
                switch (position) {
                    case 0:     //跳转我的车辆界面
                        if (PathUtils.havedLogin) {
                            mTransaction.add(R.id.ll_main_layout,new MyCarsFragment(),"MyCars");
                            mTransaction.addToBackStack("MyCars");
                        } else {
                            placeLogin();
                        }

                        break;
                    case 1:     //跳转我的收藏界面
                        if (PathUtils.havedLogin) {
                            mTransaction.add(R.id.ll_main_layout,new MyCollectFragment(),"MyCollect");
                            mTransaction.addToBackStack("MyCollect");
                        } else {
                            placeLogin();
                        }
                        break;
                    case 2:     //跳转我发表的界面
                        if (PathUtils.havedLogin) {
                            mTransaction.add(R.id.ll_main_layout,new MyNotesFragment(),"MyNotes");
                            mTransaction.addToBackStack("MyNotes");
                        } else {
                            placeLogin();
                        }
                        break;
                    case 3:     //跳转推荐给朋友界面
                        if (PathUtils.havedLogin) {
                            mTransaction.add(R.id.ll_main_layout,new LikeFriendFragment(),"LikeFriend");
                            mTransaction.addToBackStack("LikeFriend");
                        } else {
                            placeLogin();
                        }
                        break;
                    case 4:   //跳转设置界面
                        mTransaction.add(R.id.ll_main_layout,new SettingsFragment(),"Settings");
                        mTransaction.addToBackStack("Settings");
                        break;
                }
                mTransaction.commit();
            }
        });
    }
    private void placeLogin() {
        Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
    }
    private void initDate() {
        mList = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            Map<String,Object> map = new HashMap<>();
            map.put("image",images[i]);
            map.put("text",texts[i]);
            mList.add(map);
        }
        mAdapter = new SimpleAdapter(getActivity(),mList,R.layout.user_menu_item,
                new String[]{"image","text"},new int[]{R.id.iv_my_image,R.id.tv_my_text});
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        mTransaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.tv_click_login:
                if (!PathUtils.havedLogin) {
                    mTransaction.add(R.id.ll_main_layout,new LoginFragment(),"Login");
                    mTransaction.addToBackStack("Login");
                }

                break;
            case R.id.cni_header_user:
                if (PathUtils.havedLogin) {
                    mTransaction.add(R.id.ll_main_layout,new UserDataFragment(),"UserData");
                    mTransaction.addToBackStack("UserData");
                } else {
                    mTransaction.add(R.id.ll_main_layout,new LoginFragment(),"Login");
                    mTransaction.addToBackStack("Login");
                }
                break;
        }
        mTransaction.commit();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
